<template>
  <div class="sys-company">
    <AppMainHeader>
      <el-row>
        <el-col :span="20">
          <SysCompanyQueryForm @query="handleQuery" />
        </el-col>
        <el-col :span="4" class="align-right">
          <el-button type="primary" @click="handleAdd" v-hasPermi="['sys:user:add']">新增</el-button>
          <el-button type="primary" @click="handleAddUnitGroup" v-hasPermi="['sys:user:add']">新增组别</el-button>
        </el-col>
      </el-row>
    </AppMainHeader>

    <AppMainContent>
      <el-table v-loading="loading" :data="companyList">
        <el-table-column prop="rowNumber" label="序号" align="center" width="60"></el-table-column>
        <el-table-column prop="companyName" label="单位名称" min-width="10%" align="left"
                         :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="category" label="类别" min-width="8%" align="center" :show-overflow-tooltip="true"
                         :formatter="categoryFormat"></el-table-column>
        <el-table-column prop="groupName" label="组别" min-width="7%" align="center"
                         :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="linkMan" label="联系人" min-width="7%" align="center"></el-table-column>
        <el-table-column prop="mobile" label="联系电话" min-width="10%" align="center"></el-table-column>
        <el-table-column prop="safetyPermit" label="安全许可证有效期" min-width="15%" align="center"></el-table-column>
        <el-table-column prop="quality" label="资质有效期" min-width="15%" align="center"></el-table-column>
        <el-table-column prop="monitorObject" label="重点监控对象" min-width="10%" align="center"
                         :formatter="monitorObjectFormat"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding" min-width="15%">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              v-hasPermi="['system:company:add']"
              @click="handleDetail(scope.row)"
            >详情
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:company:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:company:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total>0"
        :total="total"
        :current.sync="queryParams.currPage"
        :size.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </AppMainContent>

    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px" :disabled="detailFlag">
        <el-row>
          <el-col :span="24">
            <el-form-item label="单位名称" prop="name" required>
              <el-input v-model="form.name"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="类别" prop="category">
              <el-select v-model="form.category" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in categoryOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="组别">
              <el-select v-model="form.groupId" placeholder="请选择" clearable>
                <el-option
                  v-for="item in groupOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="linkMan">
              <el-input v-model="form.linkMan"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="mobile">
              <el-input v-model="form.mobile" type="number"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="重点监控对象">
              <el-select v-model="form.monitorObject" placeholder="请选择">
                <el-option
                  v-for="dict in monitorObjectOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="资质有效期">
              <el-date-picker
                v-model="qualityArr"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="安全许可证有效期">
              <el-date-picker
                v-model="safePermitArr"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" maxlength="150" show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddCompany">取 消</el-button>
        <el-button type="primary" @click="submitAddCompanyForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增组别" :visible.sync="unitGroupOpen" width="400px" append-to-body>
      <el-form ref="unitGroupForm" :model="unitGroupForm" :rules="unitGroupRules" label-width="85px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="组别名称" prop="name" required>
              <el-input v-model="unitGroupForm.name"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddUnitGroup">取 消</el-button>
        <el-button type="primary" @click="submitAddUnitGroupForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {listCompany, addCompany, deleteCompany, updateCompany, getCompany} from "@/api/system/company";
  import {listUnitGroup, addUnitGroup} from "@/api/system/unitGroup";

  import SysCompanyQueryForm from '@/views/system/components/sys-company-query-form'

  export default {
    name: "Company",
    components: { SysCompanyQueryForm },
    data() {
      return {
        detailFlag: false,
        // 遮罩层
        loading: false,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格树数据
        companyList: [],
        // 类别数据字典
        categoryOptions: [],
        qualityArr: [],
        safePermitArr: [],
        // 单位组别下拉选择
        groupOptions: [],
        // 是否监控对象数据字典
        monitorObjectOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示新增组别弹出层
        unitGroupOpen: false,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [
            {required: true, message: "单位名称不能为空", trigger: "blur"},
            {min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur'}
          ],
          mobile: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ],
          remark: [
            {max: 150, message: '长度不超过150个字符', trigger: 'blur'}
          ]
        },
        unitGroupForm: {},
        unitGroupRules: {
          name: [
            {required: true, message: "组别名称不能为空", trigger: "blur"},
            {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
          ],
        },
        // 查询参数
        queryParams: {
          companyName: undefined,
          category: undefined,
          groupName: undefined,
          currPage: 1,
          pageSize: 10,
          orderColumn: undefined,
          orderDirection: undefined,
        }
      };
    },
    created() {
      // this.getList();
      // this.getGroupOptions();
      // this.getDicts("sys_company_category").then(response => {
      //   this.categoryOptions = response.data;
      // });
      // this.getDicts("sys_company_monitorObject").then(response => {
      //   this.monitorObjectOptions = response.data;
      // });
    },
    methods: {
      /** 类别字典翻译 **/
      categoryFormat(row, column) {
        return this.selectDictLabel(this.categoryOptions, row.category);
      },
      /** 监控对象字典翻译 **/
      monitorObjectFormat(row, column) {
        return this.selectDictLabel(this.monitorObjectOptions, row.monitorObject);
      },
      /** 查询部门列表 */
      getList() {
        this.loading = true;
        listCompany(this.queryParams).then(response => {
          this.companyList = response.data;
          this.total = response.page.total;
          this.loading = false;
        });
      },
      /** 查询单位类别列表 */
      getGroupOptions() {
        listUnitGroup().then(response => {
          this.groupOptions = response.data;
        });
      },
      // 取消按钮
      cancelAddCompany() {
        this.open = false;
        this.reset();
      },
      cancelAddUnitGroup() {
        this.unitGroupOpen = false;
        this.unitGroupReset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: '',
          name: '',
          mobile: '',
          linkMan: '',
          groupId: '',
          groupName: '',
          category: undefined,
          monitorObject: 1,
          remark: '',
          safePermit: '',
          quality: ''
        };
        this.qualityArr = []
        this.safePermitArr = []
        this.resetForm("form");
      },
      unitGroupReset() {
        this.unitGroupForm = {
          name: undefined
        };
        this.resetForm("unitGroupForm");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.detailFlag = false
        this.reset();
        if (row != undefined) {
          this.form.id = row.id;
        }
        this.open = true;
        this.title = "新增单位";
      },
      /** 新增组别 **/
      handleAddUnitGroup() {
        this.unitGroupReset();
        this.unitGroupOpen = true;
      },
      handleDetail(row) {
        this.detailFlag = true
        let id = row.companyID;
        getCompany({id}).then(response => {
          let data = response.data;
          this.form = {
            id: data.id,
            name: data.name,
            mobile: data.linkPhone,
            linkMan: data.linkMan,
            groupId: data.groupId,
            groupName: data.groupName,
            category: data.category,
            monitorObject: data.monitorObject,
            remark: data.remark
          };
          if (null !== data.qualification) {
            var qualificationArr = data.qualification.split("/");
            this.$set(this, 'qualityArr', [qualificationArr[0], qualificationArr[1]]);
          }

          if (null !== data.safetyPermit) {
            var safePermitArr = data.safetyPermit.split("/");
            this.$set(this, 'safePermitArr', [safePermitArr[0], safePermitArr[1]]);
          }
        })
        this.open = true;
        this.title = "单位详情";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.detailFlag = false
        this.reset();
        let id = row.companyID;
        getCompany({id}).then(response => {
          let data = response.data;
          this.form = {
            id: data.id,
            name: data.name,
            mobile: data.linkPhone,
            linkMan: data.linkMan,
            groupId: data.groupId,
            groupName: data.groupName,
            category: data.category,
            monitorObject: data.monitorObject,
            remark: data.remark
          };

          if (null !== data.qualification && '' !== data.qualification) {
            var qualificationArr = data.qualification.split("/");
            this.$set(this, 'qualityArr', [qualificationArr[0], qualificationArr[1]]);
          }

          if (null !== data.safetyPermit && '' !== data.safetyPermit) {
            var safePermitArr = data.safetyPermit.split("/");
            this.$set(this, 'safePermitArr', [safePermitArr[0], safePermitArr[1]]);
          }
          this.open = true;
          this.title = "修改单位";
        })
      }
      ,
      /** 提交按钮 */
      submitAddCompanyForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (null == this.qualityArr || this.qualityArr.length == 0) {
              this.form.quality = '';
            } else if (this.qualityArr.length > 0) {
              // if(this.qualityArr[1] !==undefined){
              this.form.quality = this.qualityArr[0] + '/' + this.qualityArr[1];
              // }
            }

            if (null == this.safePermitArr || this.safePermitArr.length == 0) {
              this.form.safePermit = '';
            } else if (this.safePermitArr.length > 0) {
              // if(this.safePermitArr[1] !==undefined) {
              this.form.safePermit = this.safePermitArr[0] + '/' + this.safePermitArr[1];
              // }
            }

            if (this.form.id != undefined) {
              updateCompany(this.form).then(response => {
                this.msgSuccess("修改单位成功");
                this.open = false;
                this.getList();
              });
            } else {
              addCompany(this.form).then(response => {
                this.msgSuccess("新增单位成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      }
      ,
      /** 提交新增组别 **/
      submitAddUnitGroupForm() {
        this.$refs["unitGroupForm"].validate(valid => {
          if (valid) {
            addUnitGroup(this.unitGroupForm).then(response => {
              this.msgSuccess("新增组别成功");
              this.unitGroupOpen = false;
            });
          }
        });
      }
      ,
      /** 删除按钮操作 */
      handleDelete(row) {
        let id = row.companyID;
        this.$confirm('是否确认删除单位名称为"' + row.companyName + '"的数据项?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return deleteCompany({id});
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      }
    }
  };
</script>

<style>
  input[type=number] {
    -moz-appearance: textfield;
  }

  input[type=number]::-webkit-inner-spin-button,
  input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
</style>
